﻿using Simple.Framework.Ioc;
using Simple.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*********************************************************
 * 命名空间 Simple.Framework.Load
 * 接口名称 ClassLoader
 * 开发人员：zdm
 * 创建时间：2023/11/21 9:16:20
 * 描述说明：
 * 更改历史：
 * 
 * *******************************************************/
namespace Simple.Framework.Load
{
	public class ClassLoader: IClassLoader
	{

		private List<IClassLoadProcess> classLoads;

		private IContainer container;
		/// <summary>
		/// 
		/// </summary>
		/// <param name="container"></param>
		public ClassLoader( IContainer container) {
			classLoads = new List<IClassLoadProcess>();
			this.container = container;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="classLoadProcess"></param>
		public void Register(IClassLoadProcess classLoadProcess)
		{
			if (classLoads.Any(c=>classLoadProcess==c))
			{
				return;
			}
			classLoads.Add(classLoadProcess);
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="classLoadProcesss"></param>
		public void Register(IEnumerable<IClassLoadProcess> classLoadProcesss)
		{
			foreach (var classLoadProcess in classLoadProcesss)
			{
				Register(classLoadProcess);
			}
		}
		/// <summary>
		/// 
		/// </summary>
		public void LoadClass()
		{
			if (ToolSimpleCheck.IsNullOrEmpty(classLoads))
			{
				return;
			}
			AppDomain.CurrentDomain.GetAssemblies();
			var classLoad = classLoads[0];
			Type itype = typeof(IClassLoadProcess);
			foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
			{
				foreach (var type in assembly.GetTypes().Where(t=>t.IsAssignableTo(itype)))
				{
					classLoad.Process(type);
				}
			}

			foreach (var item in classLoads)
			{
				item.Initializer();
			}
			foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
			{
				foreach (var type in assembly.GetTypes().Where(t=>!t.IsAssignableTo(itype)))
				{
					foreach (var loadProcess in classLoads)
					{
						if (loadProcess.Process(type))
						{
							container.Register(type).Autowird();
							continue;
						}
					}
				}
			}

			foreach (var item in classLoads)
			{
				item.ProcessEnd();
			}
		}

	}
}
